<template>
    <el-container>
        <el-header class="header">
            <div class="left-panel">
                <el-form class="search-form" ref="formRefSearch" :inline="true" :model="formSearch">
                    <el-form-item prop="RoleName">
                        <el-input v-model="formSearch.RoleName" placeholder="角色名称" clearable class="!w-[180px]" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" icon="Search" @click="onSearch">搜索</el-button>
                        <el-button type="info" icon="RefreshLeft" @click="resetForm(formRefSearch)">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="right-panel">
                <el-button type="primary" size="default" icon="Plus" @click="addRole">新增角色</el-button>
                <el-button type="danger" size="default" icon="Delete" @click="deleteRole">批量删除</el-button>
            </div>
        </el-header>
        <el-main class="main">
            <el-table border :data="roleArr" height="calc(100vh - 280px)" :stripe="true" :highlight-current-row="true"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="55" />
                <el-table-column type="index" label="序号" width="80px" align="center"></el-table-column>
                <el-table-column label="角色名称" prop="name" align="center">
                </el-table-column>
                <el-table-column label="角色标识" prop="code" align="center">
                </el-table-column>
                <el-table-column label="角色描述" prop="desc" align="center">
                </el-table-column>
                <el-table-column label="角色状态" prop="status" align="center">
                    <template #default="scope">
                        {{ scope.row.status == 0 ? '启用' : '禁用' }}
                    </template>
                </el-table-column>
                <el-table-column label="添加时间" prop="createTime" align="center">
                </el-table-column>
                <el-table-column label="角色操作" align="center" width="300">
                    <template #="{ row, $index }">
                        <el-button type="warning" size="default" icon="Edit" v-show="row.isSeed !== 0"
                            @click="updateRole(row)">修改</el-button>
                        <el-popconfirm :title="`您确定要删除${row.name}?`" width="250px" icon="Delete"
                            @confirm='removeRole(row.id)'>
                            <template #reference>
                                <el-button type="danger" size="default" icon="Delete"
                                    v-show="row.isSeed !== 0">删除</el-button>
                            </template>
                        </el-popconfirm>
                        <el-button type="info" size="default" icon="Menu" v-show="row.isSeed !== 0"
                            @click="handleMenu(row)">权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination class="pagination" @size-change="sizeChange" @current-change="getRole" :pager-count="9"
                v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[10, 20, 50, 100]"
                :background="true" layout="total,sizes,prev, pager, next, jumper" :total="total" />
        </el-main>
    </el-container>
    <el-dialog v-model="dialogFormVisible" :title="roleParams.id ? '修改角色' : '新增角色'">
        <el-form :model="roleParams" :rules="rules" ref="formRef">
            <el-form-item label="角色名称" label-width="100px" prop="name">
                <el-input placeholder="请您输入角色名称" v-model="roleParams.name"></el-input>
            </el-form-item>
            <el-form-item label="角色标识" label-width="100px" prop="name">
                <el-input placeholder="请您输入角色标识" v-model="roleParams.code"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" label-width="100px" prop="desc">
                <el-input type="textarea" placeholder="请您输入角色描述" v-model="roleParams.desc"></el-input>
            </el-form-item>
            <el-form-item label="是否启用" label-width="100px">
                <el-radio-group v-model="roleParams.status">
                    <el-radio :value="0">启用</el-radio>
                    <el-radio :value="1">禁用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="info" size="default" @click="cancel">取消</el-button>
            <el-button type="primary" size="default" @click="confirm">确定</el-button>
        </template>
    </el-dialog>
    <el-dialog v-model="dialogFormVisibleMenu" :title="'菜单权限'">
        <el-tree ref="treeRef" :data="menuArr" show-checkbox default-expand-all node-key="id" highlight-current
            :props="defaultProps" :check-strictly="true" />
        <template #footer>
            <el-button type="info" size="default" @click="cancelMenu">取消</el-button>
            <el-button type="primary" size="default" @click="confirmMenu">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang='ts'>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElTree } from 'element-plus'
import { getRolePageListApi, reqAddOrUpdateRoleApi, reqDeleteRoleApi, reqGetRoleMenuApi, reqUpdateRoleMenuApi } from "@/api/modules/role";
import { getMenuListApi } from "@/api/modules/menu"

let pageNo = ref<number>(1);
let limit = ref<number>(10);
let total = ref<number>(0);
let roleArr = ref([]);
let menuArr = ref([]);
const selectable = (row) => ![1].includes(row.id)
let dialogFormVisible = ref<boolean>(false)
let dialogFormVisibleMenu = ref<boolean>(false)
let roleParams = reactive({
    id: 0,
    name: '',
    code: '',
    desc: '',
    status: 0
})
let formSearch = reactive({
    RoleName: ''
})
let pageCon = reactive({
    PageNum: pageNo.value,
    PageSize: limit.value
})
const loading = ref(false);
let formRef = ref();
let formRefSearch = ref();
let deleteIds = reactive([])
const defaultProps = {
    children: 'children',
    label: 'menuTitle',
}
const treeRef = ref<InstanceType<typeof ElTree>>()
const curRow = reactive({
    roleId: 0,
    menuIds: [],
});

onMounted(async () => {
    getRole();
    getMenu();
});
const getRole = async (pageNo = 1) => {
    pageCon.PageNum = pageNo;
    let result = await getRolePageListApi({ ...formSearch, ...pageCon });
    if (result?.status == 200) {
        total.value = result.response.dataCount;
        roleArr.value = result.response.data;
    }
}
const getMenu = async () => {
    let result = await getMenuListApi()
    menuArr.value = result.response
}
const sizeChange = () => {
    getRole();
}
const InitParams = () => {
    roleParams = reactive({
        id: 0,
        name: '',
        code: '',
        desc: '',
        status: 0
    })
}
const addRole = () => {
    dialogFormVisible.value = true;
    InitParams();
    nextTick(() => {
        formRef.value.clearValidate('name');
        formRef.value.clearValidate('desc');
    })
}
const updateRole = (row: any) => {
    nextTick(() => {
        formRef.value.clearValidate('name');
        formRef.value.clearValidate('desc');
    })
    dialogFormVisible.value = true;
    Object.assign(roleParams, row);
}
const validatorName = (rule: any, value: any, callBack: any) => {
    if (value.trim().length >= 2) {
        callBack();
    } else {
        callBack(new Error('名称位数大于等于两位'))
    }
}
const validatorDesc = (rule: any, value: any, callBack: any) => {
    if (value.trim().length >= 4) {
        callBack();
    } else {
        callBack(new Error('名称位数大于等于四位'))
    }
}
const rules = {
    name: [
        { required: true, trigger: 'blur', validator: validatorName }
    ],
    desc: [
        { required: true, trigger: 'blur', validator: validatorDesc }
    ]
}
const removeRole = async (id: number) => {
    let result = await reqDeleteRoleApi(id);
    if (result.status == 200) {
        ElMessage({
            type: 'success',
            message: '删除角色成功'
        });
        getRole(roleArr.value.length > 1 ? pageNo.value : pageNo.value - 1);
    } else {
        ElMessage({
            type: 'error',
            message: '删除角色失败'
        })
    }
}
const cancel = () => {
    dialogFormVisible.value = false;
}
const confirm = async () => {
    await formRef.value.validate();
    let result: any = await reqAddOrUpdateRoleApi(roleParams);
    if (result.status == 200) {
        dialogFormVisible.value = false;
        ElMessage({
            type: 'success',
            message: roleParams.id ? '修改角色成功' : '添加角色成功'
        });
        getRole(roleParams.id ? pageNo.value : 1);
    } else {
        ElMessage({
            type: 'error',
            message: roleParams.id ? '修改角色失败' : '添加角色失败'
        });
        dialogFormVisible.value = false;
    }
}
const onSearch = () => {
    loading.value = true;
    getRole();
    loading.value = false;
}
const resetForm = (formEl) => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
}
const handleMenu = async (row) => {
    const { id } = row;
    if (id) {
        curRow.roleId = id;
        const menuIds = (await reqGetRoleMenuApi(id)).response.map(m => m.menuId);
        console.log(menuIds);
        dialogFormVisibleMenu.value = true;
        nextTick(async () => {
            treeRef.value.setCheckedKeys(menuIds);
        });
    } else {
        dialogFormVisibleMenu.value = false;
    }
}
const handleSelectionChange = (val: []) => {
    deleteIds = val
}
const deleteRole = () => {
    console.log(deleteIds)
}
const handleCheckChange = (
    data: Tree,
    checked: boolean,
    indeterminate: boolean
) => {
    console.log(data, checked, indeterminate)
}
const cancelMenu = () => {
    dialogFormVisibleMenu.value = false;
}
const confirmMenu = async () => {
    curRow.menuIds = [...treeRef.value!.getCheckedKeys(), ...treeRef.value!.getHalfCheckedKeys()]
    let result: any = await reqUpdateRoleMenuApi(curRow)
    if (result.status == 200) {
        dialogFormVisibleMenu.value = false;
        ElMessage({
            type: 'success',
            message: '权限配置成功'
        });
        getRole(roleParams.id ? pageNo.value : 1);
    } else {
        ElMessage({
            type: 'error',
            message: '权限配置失败'
        });
        dialogFormVisibleMenu.value = false;
    }
}
</script>

<style lang='scss' scoped></style>